package org.eyeTopLight.config;

import org.eyeTopLight.service.impl.MyClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    public AuthorizationServer() {
        super();
    }
    @Resource
    private TokenStore tokenStore;
    @Resource
    private MyClientDetailsService myClientDetailsService;
    @Resource
    private AuthorizationCodeServices authorizationCodeServices;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtAccessTokenConverter accessTokenConverter;

    @Autowired
    private TokenEnhancer jwtTokenEnhancer;//自定义jwt生成数据模板

    /**
     * AuthorizationServerSecurityConfigurer：
     * 用来配置令牌端点(Token Endpoint)的安全约束，可以限定哪些url资源可以访问我们的认证服务端点，主要有以下几个属性配置：
     * tokenKeyAccess：tokenkey这个endpoint当使用JwtToken且使用非对称加密时，资源服务用于获取公钥而开放的，这里指这个
     * endpoint完全公开。
     * checkTokenAccess：checkToken这个endpoint完全公开
     * allowFormAuthenticationForClients： 允许表单认证
     * @param security a fluent configurer for security features
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")                  //oauth/check_token公开
                .allowFormAuthenticationForClients()				//表单认证（申请令牌）
        ;
    }


    /**
     * 定义令牌管理服务
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices service=new DefaultTokenServices();
        service.setClientDetailsService(myClientDetailsService);//客户端详情服务
        service.setSupportRefreshToken(true);//支持刷新令牌
        service.setTokenStore(tokenStore);//令牌存储策略
        //令牌增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancers=new ArrayList<>();
        enhancers.add(jwtTokenEnhancer);//自定义JWT模板
        enhancers.add(accessTokenConverter);//转换为jwt的token
        tokenEnhancerChain.setTokenEnhancers(enhancers);
        service.setTokenEnhancer(tokenEnhancerChain);
        service.setAccessTokenValiditySeconds(3600); // 令牌默认有效期2小时
        service.setRefreshTokenValiditySeconds(3600); // 刷新令牌默认有效期2小时

        service.setTokenEnhancer(tokenEnhancerChain);
        return service;
    }

    /**
     * ClientDetailsServiceConfigurer：用来配置客户端详情服务（ClientDetailsService)
     * 客户端详情信息在这里进行初始化，你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
     * @param clients the client details configurer
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(myClientDetailsService);
    }


    /**
     * 设置授权码模式的授权码如何存取，使用数据库方式
     * @param dataSource
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    /**
     * 配置令牌（token）的访问端点和令牌服务(token
     * @param endpoints the endpoints configurer
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)//认证管理器
                .authorizationCodeServices(authorizationCodeServices)//授权码服务
                .tokenServices(tokenService())//令牌管理服务
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }
}
